const fs = require('fs');
const archiver = require('archiver');


class MyZip {
  /**
   * 压缩文件夹 zipDir(`./www`, `./zip/abc.zip`);
   * @param folderPath 
   * @param outputFilePath 
   * @returns {Promise<boolean>}
   */
  static zipDir = (folderPath, outputFilePath) => {
    return new Promise((resolve) => {
      const output = fs.createWriteStream(outputFilePath);
      const archive = archiver('zip', {
        zlib: { level: 9 } // 设置压缩级别
      });

      output.on('close', () => {
        resolve(true);
      });

      output.on('error', (err) => {
        console.error('Error occurred while compressing the folder:', err);
        resolve(false);
      });

      archive.on('error', (err) => {
        console.error('Error occurred while creating the archive:', err);
        resolve(false);
      });

      archive.pipe(output);
      archive.directory(folderPath, false); // 压缩整个文件夹，忽略文件夹本身

      archive.finalize();
    });


  }

}


module.exports = { MyZip };